from django.contrib import admin
from django.utils.html import format_html
from .models_auto import Category, QuestionAnswer, QuestionAnswerTranslation, Keyword, UserRequest
import jieba
import re

class QuestionAnswerTranslationInline(admin.TabularInline):
    model = QuestionAnswerTranslation
    extra = 1
    fields = ('language', 'question', 'answer', 'image_url', 'image_alt')

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'created_at', 'updated_at')
    search_fields = ('name',)
    list_filter = ('created_at', 'updated_at')

@admin.register(QuestionAnswer)
class QuestionAnswerAdmin(admin.ModelAdmin):
    list_display = ('sku', 'category', 'get_translations', 'created_at')
    list_filter = ('category', 'created_at')
    search_fields = ('sku', 'translations__question', 'translations__answer')
    inlines = [QuestionAnswerTranslationInline]

    def get_translations(self, obj):
        translations = obj.translations.all()
        return format_html('<br>'.join([f"{t.language}: {t.question[:50]}..." for t in translations]))
    get_translations.short_description = '翻译'

@admin.register(QuestionAnswerTranslation)
class QuestionAnswerTranslationAdmin(admin.ModelAdmin):
    list_display = ('question_answer', 'language', 'question', 'answer', 'image_preview')
    list_filter = ('language',)
    search_fields = ('question', 'answer')
    readonly_fields = ('image_preview',)

    def image_preview(self, obj):
        if obj.image_url:
            return format_html('<img src="{}" style="max-height: 100px;"/>', obj.image_url)
        return "无图片"
    image_preview.short_description = '图片预览'

@admin.register(Keyword)
class KeywordAdmin(admin.ModelAdmin):
    list_display = ('word', 'get_synonyms', 'created_at')
    search_fields = ('word', 'synonyms')
    list_filter = ('created_at',)

    def get_synonyms(self, obj):
        if obj.synonyms:
            return obj.synonyms
        return "无同义词"
    get_synonyms.short_description = '同义词'

    def save_model(self, request, obj, form, change):
        # 自动提取同义词
        if not obj.synonyms:
            # 使用jieba进行分词
            words = jieba.cut(obj.word)
            # 过滤掉停用词和单字词
            filtered_words = [w for w in words if len(w) > 1]
            if filtered_words:
                obj.synonyms = ','.join(filtered_words)
        super().save_model(request, obj, form, change)

@admin.register(UserRequest)
class UserRequestAdmin(admin.ModelAdmin):
    list_display = ('user_input', 'language_code', 'request_time', 'get_matched_questions')
    list_filter = ('language_code', 'request_time')
    search_fields = ('user_input', 'response')
    readonly_fields = ('user_input', 'language_code', 'request_time', 'response', 'matched_questions')

    def get_matched_questions(self, obj):
        questions = obj.matched_questions.all()
        return format_html('<br>'.join([f"{q.sku}: {q.translations.first().question[:50]}..." for q in questions]))
    get_matched_questions.short_description = '匹配的问题'

    def has_add_permission(self, request):
        return False  # 禁止手动添加用户请求

    def has_change_permission(self, request, obj=None):
        return False  # 禁止修改用户请求

# 添加自定义管理命令
from django.core.management.base import BaseCommand
from django.db import transaction

class Command(BaseCommand):
    help = '处理用户输入并返回匹配的答案'

    def add_arguments(self, parser):
        parser.add_argument('user_input', type=str)
        parser.add_argument('--language', type=str, default='zh-CN')

    def handle(self, *args, **options):
        user_input = options['user_input']
        language = options['language']

        # 1. 检查是否为完整SKU
        if '-' in user_input:
            sku = user_input
            matches = QuestionAnswer.objects.filter(sku=sku)
            if not matches.exists():
                # 2. 检查部分SKU
                partial_sku = user_input.split('-')[0]
                matches = QuestionAnswer.objects.filter(sku__startswith=partial_sku)

        # 3. 如果没有SKU匹配，使用关键词匹配
        if not matches.exists():
            # 提取关键词
            keywords = jieba.cut(user_input, cut_all=False)
            keyword_list = [word for word in keywords if len(word) > 1]
            
            if not keyword_list:
                keyword_list = [user_input]

            # 构建查询条件
            from django.db.models import Q
            query = Q()
            for keyword in keyword_list:
                # 直接匹配问题
                query |= Q(translations__question__icontains=keyword, translations__language=language)
                
                # 匹配关键词及其同义词
                keyword_objs = Keyword.objects.filter(
                    Q(word=keyword) | Q(synonyms__icontains=keyword)
                )
                
                for kw_obj in keyword_objs:
                    query |= Q(keywords=kw_obj)

            matches = QuestionAnswer.objects.filter(query).distinct()

        # 4. 特殊分类匹配
        if not matches.exists():
            if any(word in user_input for word in ['接线', '焊接']):
                install_category = Category.objects.filter(name__icontains='安装').first()
                if install_category:
                    matches = QuestionAnswer.objects.filter(category=install_category)

        # 记录用户请求
        with transaction.atomic():
            request = UserRequest.objects.create(
                user_input=user_input,
                language_code=language,
                response=f"找到{matches.count()}个相关答案"
            )
            request.matched_questions.set(matches)

        # 返回结果
        results = []
        for match in matches:
            translation = match.translations.filter(language=language).first()
            if translation:
                results.append({
                    'question': translation.question,
                    'answer': translation.answer,
                    'image_url': translation.image_url,
                    'image_alt': translation.image_alt or translation.question
                })

        return results